<?php

namespace app\admin\controller;

use app\admin\common\Common;
use app\admin\model\AdminModel;
use app\admin\validate\AdminValidate;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\facade\Cache;
use think\facade\Session;
use think\Request;
use think\response\Json;

class Admin extends LoginThere
{
    /**
     * @param Request $request
     * @return Json
     */
    public function admininfo(Request $request){
        if ($request->isPost()){
            $data = $request->post();
            $validate = new AdminValidate();
            if (!$validate->scene('admininfo')->check($data)) {
                return Common::result(400,$validate->getError());
            }
            return AdminModel::changeinfo($data);
        }else{
            return $this->fetch();
        }
    }


    public function changepwd(Request $request){
        if ($request->isPost()){
            $data = $request->post();
            $validate = new AdminValidate();
            if (!$validate->scene('pwd')->check($data)) {
                return Common::result(400,$validate->getError());
            }
            try {
                return AdminModel::changepwd($data);
            } catch (DataNotFoundException $e) {
                return Common::result(400,$e->getMessage());
            } catch (ModelNotFoundException $e) {
                 return Common::result(400,$e->getMessage());
            } catch (PDOException $e) {
                 return Common::result(400,$e->getMessage());
            } catch (DbException $e) {
                 return Common::result(400,$e->getMessage());
            } catch (Exception $e) {
                 return Common::result(400,$e->getMessage());
            }
        }else{
            return $this->fetch();
        }
    }

    public function geneadminkey(){
        $adminusername = Session::get('adminusername');
        $adminkey = Common::getchar(10);
        $endadminkey = md5($adminkey);
        try {
            $result = Db::name('admin')->where('username', $adminusername)->update(['admintoken' => $endadminkey]);
        } catch (PDOException $e) {
            return Common::result(400,$e->getMessage());
        } catch (Exception $e) {
            return Common::result(400,$e->getMessage());
        }
        if ($result > 0){
            Session::set('adminkey',$endadminkey);
            return Common::result(200,"生成成功",['adminkey' => $endadminkey]);
        }else{
            return Common::result(200,"生成成功");
        }
    }

    /**
     * @return Json
     */
    public static function clear_all() {
        Cache::clear();
        return Common::result(200,'清除缓存成功');
    }

    /**
     * @return Json
     */
    public function loginout(){
        Session::clear();
        return Common::result(200,'退出登录成功');
    }

}